#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
服务器模型
"""

from sqlalchemy import Column, Integer, String, Enum, Text, DateTime, Boolean, Float
import json
from sqlalchemy.sql import func
from app.core.database import Base
import enum

class ServerStatus(enum.Enum):
    """服务器状态枚举"""
    ONLINE = "online"
    OFFLINE = "offline"
    MAINTENANCE = "maintenance"
    ERROR = "error"

class Server(Base):
    __tablename__ = "servers"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, comment="服务器名称")
    hostname = Column(String(100), nullable=False, comment="主机名")
    ip_address = Column(String(45), nullable=False, comment="IP地址")
    port = Column(Integer, default=22, comment="SSH端口")
    status = Column(Enum(ServerStatus, values_callable=lambda x: [e.value for e in x]), default=ServerStatus.OFFLINE, comment="状态")
    
    # 系统信息
    os_type = Column(String(50), nullable=True, comment="操作系统类型")
    os_version = Column(String(100), nullable=True, comment="操作系统版本")
    cpu_cores = Column(Integer, nullable=True, comment="CPU核心数")
    memory_total = Column(Integer, nullable=True, comment="内存总量(MB)")
    disk_total = Column(Integer, nullable=True, comment="磁盘总量(GB)")
    
    # 实时状态
    cpu_usage = Column(Float, default=0.0, comment="CPU使用率")
    memory_usage = Column(Float, default=0.0, comment="内存使用率")
    disk_usage = Column(Float, default=0.0, comment="磁盘使用率")
    load_average = Column(Float, default=0.0, comment="负载平均值")
    network_in = Column(Float, default=0.0, comment="网络入流量(MB/s)")
    network_out = Column(Float, default=0.0, comment="网络出流量(MB/s)")
    
    # 配置信息
    ffmpeg_path = Column(String(200), default="/usr/bin/ffmpeg", comment="FFmpeg路径")
    recording_path = Column(String(500), default="/data/recordings", comment="录制路径")
    max_concurrent_tasks = Column(Integer, default=5, comment="最大并发任务数")
    
    # 认证信息
    username = Column(String(50), nullable=True, comment="SSH用户名")
    password = Column(String(100), nullable=True, comment="SSH密码")
    ssh_key = Column(Text, nullable=True, comment="SSH密钥")
    
    # 元数据
    extra_metadata = Column(Text, default="{}", comment="额外元数据 JSON格式")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    last_seen = Column(DateTime(timezone=True), nullable=True, comment="最后在线时间")
    
    def __repr__(self):
        return f"<Server(id={self.id}, name={self.name}, hostname={self.hostname})>"
    
    def to_dict(self):
        try:
            metadata_dict = json.loads(self.extra_metadata) if self.extra_metadata else {}
        except (json.JSONDecodeError, TypeError):
            metadata_dict = {}
        
        return {
            "id": self.id,
            "name": self.name,
            "hostname": self.hostname,
            "ip_address": self.ip_address,
            "port": self.port,
            "status": self.status.value,
            "os_type": self.os_type,
            "os_version": self.os_version,
            "cpu_cores": self.cpu_cores,
            "memory_total": self.memory_total,
            "disk_total": self.disk_total,
            "cpu_usage": self.cpu_usage,
            "memory_usage": self.memory_usage,
            "disk_usage": self.disk_usage,
            "load_average": self.load_average,
            "network_in": self.network_in,
            "network_out": self.network_out,
            "ffmpeg_path": self.ffmpeg_path,
            "recording_path": self.recording_path,
            "max_concurrent_tasks": self.max_concurrent_tasks,
            "username": self.username,
            "extra_metadata": metadata_dict,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "last_seen": self.last_seen.isoformat() if self.last_seen else None
        }